local ROT = require 'rot'

local Light = ROT.Class:extend()

local Feature = require 'game.proto.feature'

function Light:init(scene)
    self.scene = scene

    self.glowFov = ROT.FOV.Precise:new(function(fov, x, y)
        return not scene:getFeature(x, y).obscure
    end, { topology = 4 })

    self.glow = ROT.Lighting(function(_, x, y)
        return scene:getFeature(x, y).obscure and 0 or 0.5 -- reflectivity
    end, { range=3, passes=2 })

    self.glow:setFOV(self.glowFov)


    self.lampFov = ROT.FOV.Precise:new(function(fov, x, y)
        return not scene:getFeature(x, y).obscure
    end, { topology = 8 })

    self.lamp = ROT.Lighting(function(_, x, y)
        return scene:getFeature(x, y).obscure and 0 or 0.2 -- reflectivity
    end, { range=6, passes = 2 })

    self.lamp:setFOV(self.lampFov)
end

function Light:compute()
    local nothing = {}

    self.map=ROT.Type.Grid()

    for i, x, y, v in self.scene.feature:each() do
        local f = Feature[v] or nothing
        if f.glow then
            self.glow:setLight(x, y, f.glow)
        elseif f.lamp then
            self.lamp:setLight(x, y, f.lamp)
        end
    end

    self.glow:compute(function (x, y, color)
        self.map:setCell(x, y, color)
            -- ROT.Color.add(color, self.scene.ambientLight))
    end)

    self.lamp:compute(function (x, y, color)
        self.map:setCell(x, y,
            ROT.Color.add(color, self.map:getCell(x, y)))-- or self.scene.ambientLight))
    end)
end



local dayLength = 4800

local function dayCycle(n) return math.sin((n % dayLength) / dayLength * math.pi) end

local function tube(n) return -2 * (n - 1.5) * n^2 end


function Light:computeDaylight(turns)
        local c = dayCycle(turns)
        local c1 = tube(tube(c))
        local c2 = tube(c1)
        local c3 = tube(c2)

        return math.floor(c2 * 100 + 70),   -- r
            math.floor(c1 * 100 + 70),  -- g
            math.floor(c3 * -130 + 300),     -- b
            math.max(2, math.min(7, math.ceil(c3 * 7))) -- fov radius
end


--[[
local timesOfDay = {
    [0] = 'night',
    'predawn',
    'dawn',
    'morning',
    'midday',
    'evening',
    'dusk',
    'night',
}

local function getTimeOfDay(turns)
    local t = timesOfDay
    return t[math.ceil(((turns % dayLength) / dayLength) * #t)]
        .. ', day ' .. math.floor(turns / dayLength + 1)
end
--]]


return Light
